//
//  SegmentControl.swift
//  dcloudlive
//
//  Created by zhu xietong on 2020/5/29.
//  Copyright © 2020 douyun. All rights reserved.
//

import Foundation
import soapp
import Eelay
import AsyncDisplayKit

class SegmentControl: UIControl {
    var index:Int{
        set{
            bar.changeTo(index: newValue)
        }
        get{
            return bar.index
        }
    }
    
    
    class Style{
        var indicatorColor:UIColor = ._foreground
        var indicatorWidth:CGFloat = 40
        var indicatorHight:CGFloat = 3
        
        var normalFont:UIFont = .systemFont(ofSize: 13)
        var selectedFont:UIFont = .systemFont(ofSize: 13)
        var normalTextColor:UIColor = ._foreground
        var selectedTextColor:UIColor = ._tint
    }
    class Seg:MoDisplayNode{
      
        var normalFont:UIFont = .systemFont(ofSize: 13)
        var selectedFont:UIFont = .systemFont(ofSize: 13)
        var normalTextColor:UIColor = ._foreground
        var selectedTextColor:UIColor = ._tint
        
        var titleNode = ASDisplayNode { () -> UIView in
            return UILabel()
        }
        let bt = ASButtonNode()
        var titleLabel:UILabel{
            get{
                return titleNode.view as! UILabel
            }
        }
        override func addLayoutRules() {
            titleLabel.textAlignment = .center
            titleLabel.textColor = ._foreground
            bt.addTarget(self, action: #selector(selectItem), forControlEvents: .touchUpInside)
        }
        
        @objc func selectItem(){
            if mo.model["selected",""] == "YES"{
                return
            }
            mo.model["selected"] = "YES"
            active(ID: "change", object: mo.model)
            changeSelect(seleted: true)
        }
        
        func changeSelect(seleted:Bool)  {
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(0.15)
            UIView.setAnimationCurve(UIView.AnimationCurve.init(rawValue: 7) ?? .easeIn)
            if !seleted{
                titleLabel.textColor = normalTextColor
                titleLabel.font = normalFont
            }else{
                titleLabel.textColor = selectedTextColor
                titleLabel.font = selectedFont
            }
            UIView.commitAnimations()
        }
        
        override func mo_model_reload() {
            titleLabel.text = mo.model["name",""]
            if mo.model["selected",""] == "YES"{
                titleLabel.textColor = selectedTextColor
                titleLabel.font = selectedFont
            }else{
                titleLabel.textColor = normalTextColor
                titleLabel.font = normalFont
            }
        }
        override func specGetter() -> _Spec {
            return titleNode.Spec.addOver(bt.Spec)
        }
        
        
    }
    class Bar:JoRuleNode<Seg>{
        var index:Int{
            get{
                for one in Each<NSMutableDictionary>(list) {
                    if one["selected",""] == "YES"{
                        return one[int:"__index__",0]
                    }
                }
                return 0
            }
        }
        func changeTo(index:Int){
            let obj = list.get(node: "\(index)", defaultV: NSMutableDictionary())
            if obj["selected",""] == "YES"{
                return
            }
            if index < nodes.count{
                var i = 0
                for k in nodes {
                    
                    if k.mo.model["selected",""] == "YES"{
                        k.mo.model["selected"] = "NO"
                        k.changeSelect(seleted: false)
                    }
                    if i == index{
                        k.mo.model["selected"] = "YES"
                        k.changeSelect(seleted: true)
                    }
                    i = i + 1

                }
//                n.mo.model["selected"] = "YES"
//                n.changeSelect(seleted: true)
            }
        }
        weak var selectedSeg:Seg? = nil{
            didSet{
                oldValue?.mo.model["selected"] = "NO"
                oldValue?.changeSelect(seleted: false)
            }
        }
        override func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
            if let seg = onwer as? Seg{
                selectedSeg = seg
            }
//            let n = data["name",""]
//            for k in nodes {
//                if k.mo.model["name",""] == n{
//                    k.mo.model["selected"] = "YES"
//
//                }else{
//                    k.mo.model["selected"] = "NO"
//                }
//            }
            changIndex(data[int:"__index__",0])
        }
        
        var changIndex:(_:Int)->Void = {_ in
            
        }

        var ui:Style = Style()
        var list:NSMutableArray{
            get{
                return mo.model.get(node: nodePath, defaultV: NSMutableArray())
            }

        }
        override func mo_model_reload() {
            super.mo_model_reload()
            var subnodes = [Seg]()
            weak var wself = self
           
            
            let ui_ = self.ui
            list.list({ (dict:NSMutableDictionary, i) in
                let subkit = Seg()
                subkit.selectedFont = ui_.selectedFont
                subkit.normalFont = ui_.normalFont
                subkit.selectedTextColor = ui_.selectedTextColor
                subkit.normalTextColor = ui_.normalTextColor
                subkit.mo.controller = wself?.mo.controller
                dict["__index__"] = "\(i)"
                subkit.delegate = wself
                subkit.mo.model = dict
                subnodes.append(subkit)
            })
                   

                
            self.nodes = subnodes
            self.invalidateCalculatedLayout()
            self.setNeedsLayout()
        }
        
        
        open override func specGetter() -> _Spec {
            let childs = self.nodes.map { (n) -> _Spec in
                n[_grow(1),_shrink(1)]
            }
            let spec:_Spec = .stack(["h|0","id|list",_shrink(1)], childs: childs)
            return spec
        }
    }
    
    let bar = Bar()
    var items:[String] = [String](){
        didSet{
            let list = items.map({ (n) -> [String:Any] in
                return ["name":n]
            })
            bar.mo.model = ["list":list].mutable_dictionary
        }
    }
    public init() {
        super.init(frame: [Swidth,50])
//        eelay = [
//            [bar.view,[ee.T.L.B.R]]
//        ]
//        bar.changIndex = {[weak self]
//            i in
//            self?.changIndex(i)
//        }
//        backgroundColor = .systemGray
    }
    
    override var intrinsicContentSize: CGSize{
        return [Swidth,50]
    }
    var changIndex:(_:Int)->Void = {_ in}
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}


open class SelectBar:UIControl{
    
    public var padding = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14)
    public var line = UIView()
    public var indicatorColor:UIColor = ._foreground
    public var indicatorWidth:CGFloat = 40
    public var indicatorHeight:CGFloat = 2
    public var normalFont:UIFont = .systemFont(ofSize: 13)
    public var selectedFont:UIFont = .boldSystemFont(ofSize: 13)
    public var normalTextColor:UIColor = ._foreground
    public var selectedTextColor:UIColor = ._tint
    
    public var indicator = UIView()
    open func addLayoutRules() {
        
    }
    
    open func setTitle(str:String,for index:Int) {
        buttonWithIndex(index: index).ui.ntitle(title: str).ncolor(color: normalTextColor).font(font: normalFont).stitle(title: str).scolor(color: selectedTextColor)
    }
    
    public var items:[String] = []{
        didSet{
            self.addBts()
        }
    }
    
    open func clearBts() {
        let bts = subviews.filter { (v) -> Bool in
            if let _ = v as? UIButton{
                return true
            }
            return false
        }
        for v in bts {
            v.removeFromSuperview()
        }
    }
    open func addBts(){
        
        var i = 0
        for name in items {
            let b = buttonWithIndex(index: i)
            b.ui.ntitle(title: name).ncolor(color: normalTextColor).scolor(color: selectedTextColor)
            i = i + 1
        }
        addSubview(indicator)
        indicator.backgroundColor = indicatorColor

    }
 
    public func buttonWithIndex(index:Int)->UIButton{
        if let bt = viewWithTag(100 + index) as? UIButton{
            return bt
        }
        let bt = UIButton()
        bt.tag = index + 100
        bt.addTarget(self, action: #selector(change(sender:)), for: .touchUpInside)
        addSubview(bt)
        return bt
    }
    
    @objc func change(sender:UIButton){
        value = sender.tag - 100
        sendActions(for: .valueChanged)
    }
    
    public var value = 0{
        didSet{
            if oldValue == value{
                return
            }
            buttonWithIndex(index: oldValue).isSelected = false
            buttonWithIndex(index: value).isSelected = true
            updateIndicator()
           
        }
    }
    
    public var contentWidth:CGFloat{
        get{
            return frame.size.width - padding.left - padding.right
        }
    }
    
    public func updateIndicator() {
        let w = contentWidth/items.count.cg_floatValue
        let h = self.frame.size.height - indicatorHeight - 1
        
        let just = (w - indicatorWidth) / 2.0
        let indicatorX = value.cg_floatValue * w + just + padding.left
        indicator.frame = [indicatorX,h,indicatorWidth,indicatorHeight]
    }
    
    
    public var index = 0{
        didSet{
            if oldValue == index{
                return
            }
            value = index
        }
    }
    
    public init() {
        super.init(frame: .zero)
//        addSubview(line)
        line.backgroundColor = ._separator
        line.layer.opacity = 0.5
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        let w = contentWidth/items.count.cg_floatValue
        let h = self.frame.size.height - indicatorHeight - 1
        var i = 0
        
        for _ in items {
            let bt = buttonWithIndex(index: i)
            bt.frame = [w * i.cg_floatValue + padding.left,0,w,h]
            i = i + 1
        }
        
        line.frame = [0,(frame.height - 1),frame.width,1]
        updateIndicator()
        
    }
        
    
}
